package gk.example.activity;

import gk.example.App;
import gk.example.BaseActivity;
import gk.example.adapter.DateListAdapter;
import gk.example.bean.DateInfo;
import gk.example.bean.User;
import gk.example.util.DateTimeUtil;
import gk.example.util.ErrorCodeUtil;
import gk.example.util.ImageLoadUtil;
import gk.example.util.T;
import gk.example.view.ProgressDialog;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

import com.example.gkdate.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.special.ResideMenu.ResideMenu;
import com.special.ResideMenu.ResideMenuItem;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeConfig;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import de.hdodenhof.circleimageview.CircleImageView;

/***
 * 
 * Description:主页面
 * 
 * @author Wenk.Chan（最新修改者）
 * @version 1.0（最新版本号）
 */
public class MainActivity extends BaseActivity implements OnClickListener {
	private PullToRefreshListView mLvDateList;
	private UMSocialService mController;
	private List<DateInfo> mListDate;
	private List<User> mListUser;
	private ImageButton mBtnAnnounceDate;
	private ImageButton mBtnBack;
	private ImageButton mBtnShare;
	private TextView mTvTopTitle;
	private CircleImageView mImageMainHead;
	private ResideMenu mResideMenu;
	private ResideMenuItem mResideMenuItemHead;
	private ResideMenuItem mResideMenuItemRecord;
	private ResideMenuItem mResideMenuItemSetting;
	private ResideMenuItem mResideMenuItemFeedback;
	private ResideMenuItem mResideMenuItemAbout;
	private ResideMenuItem mResideMenuItemExit;
	private ProgressDialog mLoadingDialog;
	private Button mBtnMainAnnounce;
	private Button mBtnMainRefresh;
	private RelativeLayout mRellayNoData;
	private int markForUser = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	protected void initView() {
		setContentView(R.layout.activity_main);
		mLvDateList = (PullToRefreshListView) findViewById(R.id.list_date);
		mListDate = new ArrayList<DateInfo>();
		mListUser = new ArrayList<User>();
		mBtnAnnounceDate = (ImageButton) findViewById(R.id.btn_announce_edit);
		mTvTopTitle = (TextView) findViewById(R.id.tv_top_title);
		mBtnBack = (ImageButton) findViewById(R.id.btn_back);
		mImageMainHead = (CircleImageView) findViewById(R.id.iv_main_head);
		mBtnMainRefresh = (Button) findViewById(R.id.btn_main_refresh);
		mBtnMainAnnounce = (Button) findViewById(R.id.btn_main_announce);
		mBtnShare = (ImageButton) findViewById(R.id.btn_main_share);
		mRellayNoData = (RelativeLayout) findViewById(R.id.rellay_main_no_data);
		mLoadingDialog = new ProgressDialog();
		mResideMenu = new ResideMenu(this);
		mResideMenu.attachToActivity(this);
		mResideMenu.setScaleValue(0.6f);
		mResideMenu.setBackgroundResource(R.drawable.bg_main_side_menu);
		if (App.BmobUser.getNickName() != null) {
			mResideMenuItemHead = new ResideMenuItem(this,
					R.drawable.default_round_head, App.BmobUser.getNickName());
		}
		mResideMenuItemRecord = new ResideMenuItem(this,
				R.drawable.ic_main_menu_record, "约会记录");
		mResideMenuItemFeedback = new ResideMenuItem(this,
				R.drawable.ic_main_menu_feedback, "意见反馈");
		mResideMenuItemSetting = new ResideMenuItem(this,
				R.drawable.ic_main_menu_setting, "软件设置");
		mResideMenuItemAbout = new ResideMenuItem(this,
				R.drawable.ic_main_menu_about, "关于约吗");
		mResideMenuItemExit = new ResideMenuItem(this,
				R.drawable.ic_main_menu_exit, "退出约吗");

	}

	protected void initEvent() {
		setPullToFresh();
		checkDate();
		setShare();
		mResideMenu.addMenuItem(mResideMenuItemHead, ResideMenu.DIRECTION_LEFT);
		if (App.BmobUser.getUserHead() != null) {
			ImageLoadUtil.getInstance().setImageBackground(this, false,
					mResideMenuItemHead.setRoundHead(),
					App.BmobUser.getUserHead().getFileUrl(this), null, 64, 64);
		} else {
			mResideMenuItemHead.setRoundHead().setBackgroundResource(
					R.drawable.default_round_head);

		}
		mResideMenu.addMenuItem(mResideMenuItemRecord,
				ResideMenu.DIRECTION_LEFT);
		mResideMenu.addMenuItem(mResideMenuItemFeedback,
				ResideMenu.DIRECTION_LEFT);
		mResideMenu.addMenuItem(mResideMenuItemSetting,
				ResideMenu.DIRECTION_LEFT);
		mResideMenu
				.addMenuItem(mResideMenuItemAbout, ResideMenu.DIRECTION_LEFT);
		mResideMenu.addMenuItem(mResideMenuItemExit, ResideMenu.DIRECTION_LEFT);
		mResideMenuItemAbout.setOnClickListener(this);
		mResideMenuItemExit.setOnClickListener(this);
		mResideMenuItemFeedback.setOnClickListener(this);
		mResideMenuItemHead.setOnClickListener(this);
		mResideMenuItemRecord.setOnClickListener(this);
		mResideMenuItemSetting.setOnClickListener(this);
		mBtnAnnounceDate.setOnClickListener(this);
		mBtnMainAnnounce.setOnClickListener(this);
		mBtnMainRefresh.setOnClickListener(this);
		mBtnShare.setOnClickListener(this);
		mImageMainHead.setVisibility(View.VISIBLE);
		mBtnBack.setVisibility(View.INVISIBLE);
		mBtnShare.setVisibility(View.VISIBLE);
		mImageMainHead.setOnClickListener(this);
		if (App.BmobUser.getUserHead() != null) {
			ImageLoadUtil.getInstance().setImageBackground(this, false,
					mImageMainHead,
					App.BmobUser.getUserHead().getFileUrl(this), null, 32, 32);
		}
		mLvDateList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				App.DateInfo = mListDate.get(position - 1);
				App.Announcer = mListDate.get(position - 1).getAnnouncer();
				finish();
				startActivity(new Intent(MainActivity.this,
						AttendActivity.class));
			}
		});
		mTvTopTitle.setText("约会");

	}

	private static final int LIMIT = 10;
	private int currentPage = 0;

	public static final int PULL_MORE = 0X11;
	public static final int PULL_FRESH = 0X12;

	private DateListAdapter mDateListAdapter;

	/**
	 * 
	 * 描述：获取数据的类
	 * 
	 * @param page
	 *            读取数据的页数
	 * @param actionType
	 *            当前上下还是下拉
	 * @param loading
	 *            布尔型,是否已经第一次加载
	 * @return void
	 */
	private void getAllData(int page, final int actionType,
			final boolean loading) {
		mDateListAdapter = new DateListAdapter(this, mListDate, mListUser);
		BmobQuery<DateInfo> query = new BmobQuery<DateInfo>();
		query.setLimit(LIMIT);
		query.setSkip(LIMIT * page);
		query.order("-createdAt");
		query.findObjects(this, new FindListener<DateInfo>() {

			@Override
			public void onSuccess(List<DateInfo> arg0) {
				if (actionType == PULL_FRESH) {
					currentPage = 0;
					mListDate.clear();
				}
				if (arg0.size() > 0) {
					mRellayNoData.setVisibility(View.INVISIBLE);
					getUserData(actionType, loading, arg0, true);
				} else {
					if (mListDate.size() == 0) {
						T.showShort(MainActivity.this, "无数据");
						mRellayNoData.setVisibility(View.VISIBLE);
						mDateListAdapter.notifyDataSetChanged();
					} else {
						T.showShort(MainActivity.this, "无更多数据");
						mDateListAdapter.notifyDataSetChanged();
					}

				}
				mLvDateList.onRefreshComplete();
				mLoadingDialog.dismiss();
			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil
						.Errorshow(MainActivity.this, arg0, "加载失败,请检查网络设置");
				mRellayNoData.setVisibility(View.VISIBLE);
				mListDate.clear();
				mListUser.clear();
				mDateListAdapter.notifyDataSetChanged();
				mLvDateList.onRefreshComplete();
				mLoadingDialog.dismiss();
			}
		});

	}

	/**
	 * 
	 * 描述： 判断约会是否过期,自动结束
	 * 
	 * @return void
	 */
	private void checkDate() {
		mLoadingDialog.show(getSupportFragmentManager(), "LOADING_DIALOG");
		BmobQuery<DateInfo> query = new BmobQuery<DateInfo>();
		query.findObjects(this, new FindListener<DateInfo>() {

			@Override
			public void onSuccess(List<DateInfo> arg0) {
				for (int i = 0; i < arg0.size(); i++) {
					if (DateTimeUtil.isAfter(arg0.get(i).getDateDate()
							.split(" ")[0]
							+ " " + arg0.get(i).getDateTime())) {
						endPastDate(arg0.get(i));
					}
				}

				getAllData(0, PULL_FRESH, true);
			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil
						.Errorshow(MainActivity.this, arg0, "加载失败,请检查网络设置");
				mRellayNoData.setVisibility(View.VISIBLE);
				mListDate.clear();
				mListUser.clear();
				if (mDateListAdapter != null) {
					mDateListAdapter.notifyDataSetChanged();
				}
				mLoadingDialog.dismiss();
			}
		});

	}

	/**
	 * 
	 * 描述：结束过期的约会
	 * 
	 * @param dateInfo
	 *            要结束的约会信息对象
	 * @return void
	 */
	private void endPastDate(DateInfo dateInfo) {
		dateInfo.setDateStatus(0);// 0代表结束约会
		dateInfo.update(this, new UpdateListener() {

			@Override
			public void onSuccess() {
			}

			@Override
			public void onFailure(int arg0, String arg1) {
				ErrorCodeUtil
						.Errorshow(MainActivity.this, arg0, "加载失败,请检查网络设置");
				mRellayNoData.setVisibility(View.VISIBLE);
				mListDate.clear();
				mListUser.clear();
				mDateListAdapter.notifyDataSetChanged();
			}
		});

	}

	/**
	 * 
	 * 描述： 上下拉刷新的相关设置
	 * 
	 * @return void
	 */
	private void setPullToFresh() {
		mLvDateList.setMode(Mode.BOTH);
		mLvDateList
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {

						getAllData(0, PULL_FRESH, false);
					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						getAllData(currentPage, PULL_MORE, false);
					}
				});

	}

	/**
	 * 
	 * 描述：获取用户数据
	 * 
	 * @param actionType
	 * @param loading
	 * @param dateInfo
	 * @return void
	 */
	private void getUserData(final int actionType, final boolean loading,
			final List<DateInfo> dateInfo, final boolean first) {
		BmobQuery<User> query = new BmobQuery<User>();
		query.addWhereMatches("objectId", dateInfo.get(markForUser)
				.getAnnouncer().getObjectId());
		query.findObjects(this, new FindListener<User>() {

			@Override
			public void onSuccess(List<User> arg0) {
				if (actionType == PULL_FRESH) {
					currentPage = 0;
					mListDate.clear();
				}
				if (first) {
					mListUser.clear();
				}
				for (int i = 0; i < dateInfo.size(); i++) {
					if (dateInfo.get(i).getDateStatus() != 0) {
						mListDate.add(dateInfo.get(markForUser));
					}
				}
				mListUser.add(arg0.get(0));
				if (mListDate.size() > (markForUser + 1)) {
					markForUser = markForUser + 1;
					getUserData(actionType, loading, dateInfo, false);
					return;
				}

				markForUser = 0;
				currentPage++;
				if (actionType == PULL_MORE) {
					mDateListAdapter.notifyDataSetChanged();
				} else {
					mLvDateList.setAdapter(mDateListAdapter);
					if (!loading && actionType == PULL_FRESH) {
						T.showShort(MainActivity.this, "刷新成功");
					}
				}
			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil
						.Errorshow(MainActivity.this, arg0, "加载失败,请检查网络设置");
				mRellayNoData.setVisibility(View.VISIBLE);
				mListDate.clear();
				mListUser.clear();
				mDateListAdapter.notifyDataSetChanged();
			}
		});
	}

	/**
	 * 设置点击事件
	 */
	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.iv_main_head:
			mResideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
			break;
		case R.id.btn_announce_edit:
			startActivity(new Intent(this, AnnounceActivity.class));
			finish();
			break;
		case R.id.btn_main_announce:
			startActivity(new Intent(this, AnnounceActivity.class));
			finish();
			break;
		case R.id.btn_main_refresh:
			getAllData(10, PULL_FRESH, true);
			break;
		case R.id.btn_main_share:
			mController.openShare(this, false);
			break;
		default:
			if (v == mResideMenuItemRecord) {
				startActivity(new Intent(this, DateRecordActivitiy.class));
			} else if (v == mResideMenuItemFeedback) {
				startActivity(new Intent(this, FeedBackActivity.class));
			} else if (v == mResideMenuItemSetting) {
				startActivity(new Intent(this, SettingActivity.class));
			} else if (v == mResideMenuItemAbout) {
				startActivity(new Intent(this, AboutActivity.class));
			} else if (v == mResideMenuItemHead) {
				startActivity(new Intent(this, PersonalInfoActivity.class));
				finish();
			}
			break;
		}
	}

	private void setShare() {
		mController = UMServiceFactory.getUMSocialService("com.umeng.share");
		mController.setShareContent("来自广科约吗-广科人自己的社交App");
		SocializeConfig localSocializeConfig = this.mController.getConfig();
		SHARE_MEDIA[] arrayOfSHARE_MEDIA = new SHARE_MEDIA[2];
		arrayOfSHARE_MEDIA[0] = SHARE_MEDIA.SINA;
		arrayOfSHARE_MEDIA[1] = SHARE_MEDIA.TENCENT;
		localSocializeConfig.removePlatform(arrayOfSHARE_MEDIA);
		UMWXHandler localUMWXHandler1 = new UMWXHandler(this,
				"wx70dd3d0545e4eac7", "de012948a1369e48e20dad8c0dc9a529");
		WeiXinShareContent localWeiXinShareContent = new WeiXinShareContent();
		localWeiXinShareContent.setShareContent("来自广科约吗-广科人自己的社交App");
		localWeiXinShareContent.setTitle("自广科约吗");
		localWeiXinShareContent.setTargetUrl("http://gkdate.bmob.cn");
		localWeiXinShareContent.setShareMedia(new UMImage(this, BitmapFactory
				.decodeResource(getResources(), 2130837625)));
		mController.setShareMedia(localWeiXinShareContent);
		localUMWXHandler1.addToSocialSDK();
		UMWXHandler localUMWXHandler2 = new UMWXHandler(this,
				"wx70dd3d0545e4eac7", "de012948a1369e48e20dad8c0dc9a529");
		localUMWXHandler2.setToCircle(true);
		localUMWXHandler2.addToSocialSDK();
		CircleShareContent localCircleShareContent = new CircleShareContent();
		localCircleShareContent.setShareContent("来自广科约吗-广科人自己的社交App");
		localCircleShareContent.setTitle("广科约吗");
		localCircleShareContent.setTargetUrl("http://gkdate.bmob.cn");
		localCircleShareContent.setShareMedia(new UMImage(this, BitmapFactory
				.decodeResource(getResources(), 2130837625)));
		mController.setShareMedia(localCircleShareContent);
		UMQQSsoHandler localUMQQSsoHandler = new UMQQSsoHandler(this,
				"1103528553", "qPPVhJLISq6KejTe");
		localUMQQSsoHandler.setTargetUrl("http://gkdate.bmob.cn");
		localUMQQSsoHandler.addToSocialSDK();
		QZoneSsoHandler localQZoneSsoHandler = new QZoneSsoHandler(this,
				"1103528553", "qPPVhJLISq6KejTe");
		localQZoneSsoHandler.setTargetUrl("http://gkdate.bmob.cn");
		localQZoneSsoHandler.addToSocialSDK();
	}

	protected void onResume() {
		super.onResume();
		if (App.BmobUser.getUserHead() != null) {
			ImageLoadUtil.getInstance().setImageBackground(this, false,
					this.mImageMainHead,
					App.BmobUser.getUserHead().getFileUrl(this), null, 32, 32);
		}
		if (App.BmobUser.getUserHead() != null) {
			ImageLoadUtil.getInstance().setImageBackground(this, false,
					this.mResideMenuItemHead.setRoundHead(),
					App.BmobUser.getUserHead().getFileUrl(this), null, 64, 64);
		}
	}
}